package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ItemMsgTable {
  private static final Log _log = LogFactory.getLog(ItemMsgTable.class);
  
  private static final ArrayList<Integer> _idList = new ArrayList<>();
  
  private static ItemMsgTable _instance;
  
  public static ItemMsgTable get() {
    if (_instance == null)
      _instance = new ItemMsgTable(); 
    return _instance;
  }
  
  private static void updata_name(int item_id) {
    Connection cn = null;
    PreparedStatement ps = null;
    String itemname = ItemTable.get().getTemplate(item_id).getName();
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("UPDATE `w_掉落广播系统` SET `名称`=? WHERE `itemid`=?");
      int i = 0;
      ps.setString(++i, "公告->" + itemname);
      ps.setInt(++i, item_id);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
  }
  
  public void reload() {
    _idList.clear();
    load();
  }
  
  public void load() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection con = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    try {
      con = DatabaseFactory.get().getConnection();
      pstm = con.prepareStatement("SELECT * FROM `w_掉落广播系统`");
      rs = pstm.executeQuery();
      while (rs.next()) {
        int item_id = rs.getInt("itemid");
        if (!_idList.contains(Integer.valueOf(item_id)))
          _idList.add(Integer.valueOf(item_id)); 
        String note = rs.getString("名称");
        if (!note.contains("=>"))
          updata_name(item_id); 
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(pstm);
      SQLUtil.close(con);
    } 
    _log.info("载入打宝公告物编号数量: " + _idList.size() + "(" + timer.get() + "ms)");
  }
  
  public boolean contains(int item_id) {
    return _idList.contains(Integer.valueOf(item_id));
  }
}
